package co.dreamapps.dodoattack.model;

import co.dreamapps.dodoattack.model.Dodo;
import protocol.Print;
import protocol.RoomConnection;
import protocol.XmlParser;

public class RoomManagerDodoGame {

	/**
	 * Message constants
	 */
	private static final String TAG = "TAG";
	private static final String VALUE = "VALUE";
	private static final String JUMP = "JUMP";
	private static final String HORIZONTAL_MOVE = "HORIZON";
	private static final String EGG = "EGG";

	/**
	 * Entities
	 */
	public Dodo dodo;
	private long lastHorizontalUpdate;

	/**
	 * Connection
	 */
	private RoomConnection room;
	private boolean isRacing;

	public RoomManagerDodoGame(RoomConnection room, boolean isRacing) {
		this.room = room;
		this.isRacing = isRacing;
	}

	public void dodoJump(int jumpingTimes, int actualY, boolean priority) {
		room.sendMessage('<' + TAG + '>' + JUMP + "</" + TAG + "><" + VALUE + '>' + jumpingTimes + " " + actualY + "</" + VALUE + ">", priority ? 2 : 1);
	}

	public boolean dodoHorizontalMove(int x, boolean moving) {
		if (moving) {
			if (System.currentTimeMillis() - lastHorizontalUpdate > 500) {
				room.sendMessage('<' + TAG + '>' + HORIZONTAL_MOVE + "</" + TAG + "><" + VALUE + '>' + x + "</" + VALUE + ">");
				lastHorizontalUpdate = System.currentTimeMillis();
				return true;
			}
		} else if (System.currentTimeMillis() - lastHorizontalUpdate > 250) {
			room.sendMessage('<' + TAG + '>' + HORIZONTAL_MOVE + "</" + TAG + "><" + VALUE + '>' + x + "</" + VALUE + ">");
			lastHorizontalUpdate = System.currentTimeMillis();
			return true;
		}
		return false;
	}

	public void onNewMessage(String message) {
		try {
			String tag = XmlParser.readByTag(message, TAG, 0);
			String value = XmlParser.readByTag(message, VALUE, XmlParser.guessNextLimit(TAG, tag, 0));
			if (tag == null || value == null) {
				Print.print(message);
				return;
			} else {
				Print.print("Tag: " + tag + " Value: " + value);
			}
			if (isRacing) {
				if (tag.equals(EGG)) {
					// Do something
				}
			} else {
				if (tag.equals(JUMP)) {
					String parts[] = value.split(" ");
					int jumpingTimes = Integer.valueOf(parts[0]);
					int actualY = Integer.valueOf(parts[1]);
					dodo.jump(jumpingTimes, actualY);
				} else if (tag.equals(HORIZONTAL_MOVE)) {
					int x = Integer.valueOf(value);
					dodo.setX(x);
				}
			}
		} catch (Exception e) {
			Print.print("RoomManagerDododGame - onNewMessage() - Exception!!");
		}
	}

}
